import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/expert/expert_top_logic.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/expert/top/league_top_list_view.dart';
import 'package:sports_new/view/expert/top/top_list_view.dart';
import 'package:sports_new/view/home/qkd_carousel_view.dart';
import 'package:sports_new/widgets/base/qkd_bottomsheet.dart';
import 'package:sports_new/widgets/base/qkd_indicator.dart';
import '../../../widgets/base/qkd_text.dart';

class ExpertTopPage extends StatefulWidget {
  const ExpertTopPage({super.key, this.showAppBar = true});

  final bool showAppBar;
  @override
  State<ExpertTopPage> createState() => _ExpertTopPageState();
}

class _ExpertTopPageState extends State<ExpertTopPage>
    with TickerProviderStateMixin {
  late final ExpertTopLogic logic;

  @override
  void initState() {
    logic = Get.put(ExpertTopLogic(showAppBar: widget.showAppBar));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.showAppBar) {
      return GetBuilder<ExpertTopLogic>(builder: (logic) {
        return Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Colours.transparent, Colours.white],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  stops: [0.05, 0.07])),
          child: Stack(alignment: AlignmentDirectional.center, children: [
            TabBarView(
                physics: const NeverScrollableScrollPhysics(),
                controller: logic.controller,
                children: List.generate(2, (index) => page(index))),
            Positioned(bottom: 32, child: choiceBar())
          ]),
        );
      });
    } else {
      return GetBuilder<ExpertTopLogic>(builder: (logic) {
        return Scaffold(
          backgroundColor: Colours.white,
          appBar: Styles.appBar(
              title: Styles.tabbar(
            tabs: [
              Image.asset(
                logic.tabIndex == 0
                    ? Utils.getImgPath("zq_choose.png")
                    : Utils.getImgPath("zq_unchoose.png"),
                width: 68,
                height: 44,
              ),
              Image.asset(
                  logic.tabIndex == 1
                      ? Utils.getImgPath("lq_choose.png")
                      : Utils.getImgPath("lq_unchoose.png"),
                  width: 68,
                  height: 44),
            ],
            controller: logic.controller,
            scrollable: true,
            labelPadding: EdgeInsets.zero,
            labelColor: Colours.white,
            indicator: const QkdIndicator.none(),
            unselectedLabelColor: Colours.white,
            onTap: (value) {
              setState(() {
                logic.tabIndex = value;
              });
            },
          )),
          body: Container(
            decoration: const BoxDecoration(
                border:
                    Border(top: BorderSide(color: Colours.greyEE, width: 0.5))),
            child: ExtendedTabBarView(
                controller: logic.controller,
                children: List.generate(2, (index) => page(index))),
          ),
        );
      });
    }
  }

  Widget choiceBar() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(17),
              boxShadow: [
                BoxShadow(
                    offset: const Offset(0, 4),
                    color: Colours.main.withOpacity(0.1),
                    blurRadius: 4)
              ]),
          height: 34,
          child: Stack(
            children: [
              Positioned(
                left: 2,
                right: 2,
                top: 1,
                bottom: 1,
                child: Container(
                  height: 34,
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: Colours.main.withOpacity(0.4), width: 0.5),
                      borderRadius: BorderRadius.circular(17),
                      color: Colours.white),
                ),
              ),
              Row(children: [
                item('足球', 'top_zq.png', 0),
                item('篮球', 'top_lq.png', 1),
              ]),
            ],
          ),
        ),
      ],
    );
  }

  Widget item(String title, String selectImage, int index) {
    bool select = index == logic.tabIndex;
    return GestureDetector(
      onTap: () {
        logic.tabIndex = index;
        logic.controller.animateTo(index);
        update();
      },
      child: Container(
        height: 36,
        width: 66,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          gradient: select
              ? const LinearGradient(
                  colors: [Color(0xFFF54D4F), Color(0xFFF53C6A)],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)
              : null,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          if (select)
            Image.asset(
              Utils.getImgPath(selectImage),
              width: 16,
            ),
          const SizedBox(width: 2),
          QkdText(title,
              color: select ? Colours.white : Colours.main, fontSize: 12)
        ]),
      ),
    );
  }

  Widget page(int index) {
    List<String> title = ['人气榜', '连红榜', '命中榜', '回报榜', if (index == 0) '赛事榜'];
    return EasyRefresh.builder(
      controller: logic.refreshController,
      scrollController: logic.scrollController,
      onRefresh: logic.getRefresh,
      header: Styles.refreshHeader(
          position: IndicatorPosition.locator, clamping: true),
      childBuilder: (BuildContext context, ScrollPhysics physics) =>
          ExtendedNestedScrollView(
              physics: physics,
              onlyOneScrollInBody: true,
              controller: logic.scrollController,
              headerSliverBuilder: (context, innerBoxIsScrolled) {
                return <Widget>[
                  const HeaderLocator.sliver(clearExtent: false),
                  SliverToBoxAdapter(
                    child: header(index)
                        .paddingOnly(top: widget.showAppBar ? 0 : 8),
                  )
                ];
              },
              body: Column(children: [
                SizedBox(
                  height: 40,
                  child: Styles.tabbar(
                    tabs: title.map((e) => QkdText(e)).toList(),
                    controller:
                        index == 0 ? logic.zqController : logic.lqController,
                    labelColor: Colours.main,
                    onTap: (value) => Utils.onEvent("expert_rank_tab",
                        params: {"tab": title[value]}),
                  ),
                ),
                Expanded(
                  child: ExtendedTabBarView(
                      controller:
                          index == 0 ? logic.zqController : logic.lqController,
                      children: [
                        TopListView(TopType.renqi, index + 1,
                            physics: physics, onlySale: logic.onlySale == "1"),
                        TopListView(TopType.lianhong, index + 1,
                            physics: physics, onlySale: logic.onlySale == "1"),
                        TopListView(TopType.mingzhong, index + 1,
                            physics: physics, onlySale: logic.onlySale == "1"),
                        TopListView(TopType.huibao, index + 1,
                            physics: physics, onlySale: logic.onlySale == "1"),
                        if (index == 0)
                          LeagueTopListView(index + 1,
                              physics: physics, onlySale: logic.onlySale == "1")
                      ]),
                )
              ])),
    );
  }

  Widget header(int index) {
    List<ResourceEntity> lbt = Get.find<ResourceService>().lbt.filter((item) =>
        item.button == (index == 0 ? 'expert_top_zq' : 'expert_top_lq'));
    return Padding(
      padding: EdgeInsets.only(top: widget.showAppBar ? 8 : 0, bottom: 10),
      child: Stack(
        children: [
          QkdCarouselView(
            carousels: lbt,
            aspectRatio: 359 / 120,
            radius: 8,
            padding: 8,
            dotBottom: 20,
            needTitle: false,
            needDot: lbt.length != 1,
          ),
          Positioned(
            right: 8,
            bottom: 16,
            child: GestureDetector(
              onTap: () => onTapRule(index),
              child: Container(
                width: 66,
                height: 25,
                alignment: Alignment.center,
                // padding: EdgeInsets,
                padding: const EdgeInsets.only(left: 1),
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Color(0xFFFFF7BD), Color(0xFFFFB444)]),
                    borderRadius:
                        BorderRadius.horizontal(left: Radius.circular(12.5))),
                child: const QkdText(
                  '上榜规则',
                  fontSize: 12,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  onTapRule(int index) {
    Utils.onEvent("expert_rank_rule");
    final tips = Get.find<ResourceService>().tips.filter((item) =>
        item.button ==
        (index == 0 ? 'expert_top_zq_rules' : 'expert_top_lq_rules'));
    if (tips.isNotEmpty) {
      Get.bottomSheet(
          QkdBottomSheet(
              title: tips.first.title,
              scrollable: true,
              child: SizedBox(
                height: 500,
                child: SingleChildScrollView(
                  child: QkdText(
                    tips.first.content!,
                    color: Colours.grey66,
                  ),
                ),
              )),
          isScrollControlled: true);
    }
  }
}
